/**
 * Copyright 2016-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.inmorn.extspring.quartz;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.SchedulerException;
import org.quartz.impl.matchers.GroupMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.inmorn.extspring.context.BeanHolder;
import com.inmorn.extspring.util.StringUtils;

/**
 * 抽象JOB类,方便获取JOB信息及指定Service
 * @author Jeff.Li
 * 2016-12-20
 */
public abstract class AbstractJobBean<JOB,BIZ> implements Job{
	
	private Class<?> clazz;
	private Class<?> serviceClazz;
	private static final Logger LOG = LoggerFactory
			.getLogger(AbstractJobBean.class);
	
	/**
	 * 当前任务组总的线程数,组中各线程都可见
	 */
	protected int groupThreadCount = 0;
	
	/**
	 * 子类是否需要看到当前任务组的任务总数
	 */
	protected boolean lookGroupThreadCount = false;
	
	@SuppressWarnings("unchecked")
	public AbstractJobBean(){
		try{
			/**
			 * 根据泛型获取JOB class和bizimpl class
			 */
			Type genType = this.getClass().getGenericSuperclass();  
			Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
	        if(clazz == null) clazz = ((Class<JOB>) params[0]);
	        if(serviceClazz == null) serviceClazz = ((Class<BIZ>) params[1]);
		}catch(Exception e){
			
		}
	}
	
	public AbstractJobBean(Class<?> clazz,Class<?> serviceClazz){
		if(this.clazz == null) this.clazz = clazz;
		if(this.serviceClazz == null) this.serviceClazz = serviceClazz;
	}
	
	public AbstractJobBean(Class<?> clazz,Class<?> serviceClazz,
			boolean lookGroupThreadCount){
		if(this.clazz == null) this.clazz = clazz;
		if(this.serviceClazz == null) this.serviceClazz = serviceClazz;
		this.lookGroupThreadCount = lookGroupThreadCount;
	}
	
	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		ScheduleJob scheduleJob = null;
		long begin = System.currentTimeMillis();
		try{
			if(clazz != null){
				scheduleJob = (ScheduleJob) context.getJobDetail().getJobDataMap().get(clazz.getSimpleName() + ".group");
				if(lookGroupThreadCount){
					try {
						Set<JobKey> jobKeys = context.getScheduler().getJobKeys(GroupMatcher.jobGroupEquals(scheduleJob.getJobGroup()));
						if(jobKeys != null){
							groupThreadCount = jobKeys.size();
						}
					} catch (SchedulerException e) {
						e.printStackTrace();
					}
				}
			}
			Object service = null;
			if(serviceClazz != null){
				service = BeanHolder.getBean(StringUtils.firstToLowerCase(serviceClazz.getSimpleName()));
			}
			if(LOG.isInfoEnabled() && scheduleJob != null){
				LOG.info(">>>>>>>>>>>>>>>>>>>>>>>>>>JOB:" + clazz.getSimpleName() + ", current JobName:" + scheduleJob.getJobName() + " Begin");
			}
			/**
			 * 调用JOB
			 */
			begin = System.currentTimeMillis();
			run(context , scheduleJob , service);
			if(LOG.isInfoEnabled() && scheduleJob != null){
				LOG.info("<<<<<<<<<<<<<<<<<<<<<<<<<<JOB:" + clazz.getSimpleName() + ", current JobName:" + scheduleJob.getJobName() + " End");
			}
		}finally{
			if(scheduleJob != null){
				scheduleJob.setLastTimeConsuming(System.currentTimeMillis() - begin);
				scheduleJob.setLastExecuteTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				scheduleJob.setExecuteTotalCount(scheduleJob.getExecuteTotalCount() + 1);
			}
		}
	}

	/**
	 * 调用执行
	 * @param context
	 * @param scheduleJob
	 * @param service
	 */
	public abstract void run(JobExecutionContext context ,ScheduleJob scheduleJob,Object service);
}